import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { ChatSession, ChatMessage, PaginatedResponse } from '../../types';

interface ChatState {
  sessions: ChatSession[];
  currentSession: ChatSession | null;
  messages: ChatMessage[];
  total: number;
  loading: boolean;
  error: string | null;
  searchKeyword: string;
  filters: {
    status?: string;
    shopId?: string;
    customerId?: string;
  };
  pagination: {
    page: number;
    limit: number;
  };
  onlineUsers: string[];
  typingUsers: { [sessionId: string]: string[] };
}

const initialState: ChatState = {
  sessions: [],
  currentSession: null,
  messages: [],
  total: 0,
  loading: false,
  error: null,
  searchKeyword: '',
  filters: {},
  pagination: {
    page: 1,
    limit: 20,
  },
  onlineUsers: [],
  typingUsers: {},
};

export const fetchSessions = createAsyncThunk(
  'chat/fetchSessions',
  async (params: any, { rejectWithValue }) => {
    try {
      return { data: [], total: 0 } as PaginatedResponse<ChatSession>;
    } catch (error: any) {
      return rejectWithValue(error.message || '获取会话列表失败');
    }
  }
);

const chatSlice = createSlice({
  name: 'chat',
  initialState,
  reducers: {
    setCurrentSession: (state, action) => {
      state.currentSession = action.payload;
    },
    addMessage: (state, action) => {
      state.messages.push(action.payload);
    },
    updateMessage: (state, action) => {
      const index = state.messages.findIndex(m => m._id === action.payload._id);
      if (index !== -1) {
        state.messages[index] = action.payload;
      }
    },
    setOnlineUsers: (state, action) => {
      state.onlineUsers = action.payload;
    },
    setTypingUsers: (state, action) => {
      const { sessionId, users } = action.payload;
      state.typingUsers[sessionId] = users;
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchSessions.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchSessions.fulfilled, (state, action) => {
        state.loading = false;
        state.sessions = action.payload.data;
        state.total = action.payload.total;
      })
      .addCase(fetchSessions.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { 
  setCurrentSession, 
  addMessage, 
  updateMessage, 
  setOnlineUsers, 
  setTypingUsers, 
  clearError 
} = chatSlice.actions;
export default chatSlice.reducer;
